/*
 * @copyright: Huang Ding
 * @Author: ding-cx
 * @Date: 2020-12-29 08:44:29
 * @LastEditors: ding-cx
 * @LastEditTime: 2021-04-02 18:13:47
 * @Description: file content
 */
import {
  ref,
  reactive,
  inject,
  watch,
  computed,
  getCurrentInstance
} from "@vue/composition-api"

import useCrudHook from "@/hooks/crud"

import svs_sys_menus from "@/service/sys/menus"

import MenuSelect from './MenuSelect.vue'

import objectDeepClone from '@/utils/objectDeepClone'

export default {
  name:"sys-menus",
  components: {
    MenuSelect,
  },
  setup(props, ctx) {
    const setups = {
      props,
      ctx,
      root: ctx.root,
      that: getCurrentInstance()
    }
    const message = inject("globalMessage");

    const cruds = useTable(setups);

    const leftTrees = useLeftTree(setups, cruds);

    const exports = {};

    const getRouteMenuList = () => {
      svs_sys_menus.getRouteMenuTree().then(data => {
        console.log(data);
        leftTrees.tree.data = data;
        // 将获取到的数据赋值给级联菜单。
        const col = cruds.option.table.column.find(item => item.prop === "parent_menu_id")
        if (col) {
          const opt = col.form.componentProps.options;
          opt.splice(1, opt.length - 1, ...data)
        }
      })

    }
    getRouteMenuList();


    /** 增、改 、表单数据处理转化。 */
    function addEditTrans(formData) {
      const sendData = objectDeepClone(formData)
      if (Array.isArray(sendData.parent_menu_id)) {
        sendData.parent_menu_id = sendData.parent_menu_id[sendData.parent_menu_id.length - 1] || 0;
      } else {
        // 非数组情况，可能是null，数值。则数值不变，null转为0.
        sendData.parent_menu_id = sendData.parent_menu_id > 0 ? sendData.parent_menu_id : 0;
      }
      console.log(sendData);
      return sendData;
    }
    exports.addSubmit = (formData, loading, done) => {
      console.log(formData);
      // loading();
      const sendData = addEditTrans(formData)
      // return
      // sendData.
      svs_sys_menus.post(sendData).then(res => {
        console.log(res);
        loading();
        message.saveSuccess();
        getRouteMenuList();
      })
    }

    exports.editSubmit = (formData, loading, done) => {
      console.log(formData);
      // loading();
      const sendData = addEditTrans(formData)
      // return
      // sendData.
      svs_sys_menus.put(sendData.id, sendData).then(res => {
        console.log(res);
        cruds.refresh();
        loading();
        message.saveSuccess();
        done();
      })
    }

    // 行删除
    exports.rowDel = (scope) => {
      console.log(scope.row.id);
      setups.root.$confirm('确定要删除此内容吗？', '请确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        svs_sys_menus.delete(scope.row.id).then(res => {
          console.log(res);
          getRouteMenuList();
          cruds.refresh();
          if (res.affectedRows >= 0) {
            setups.root.$message.success("删除成功！")
          } else {
            setups.root.$message.error("删除失败！")
          }
        })
      }).catch(() => {
        // setups.root.$message.error("操作失败！")

      });
    }





    return {
      ...cruds,
      ...exports,
      ...leftTrees,
    }

  }
}

function useTable(setups) {
  const crudObj = ref({
    // parent_menu_id: [],
    icon:""
  })
  const cruds = useCrudHook({
    crudOption: {},
    getConfig(page, condition) {
      const config = svs_sys_menus.getRouteListConfigByTreeNode();
      config.data.idList = condition.idList;
      config.data.page = [page.size, page.offset]
      return config;
    },
    searchFormToCondition(form) {
      return []
    },
    reduceHeight: 250,
  });

  setups.that.$on('get-list', (data) => {
    console.log(data);
  })

  cruds.option.table.rowMenuColumn.fixed = 'right';
  cruds.option.table.column = [{
      label: "菜单名称",
      prop: "title",
      form: {
        component: "el-input",
        componentProps: {
          placeholder: "菜单名称"
        },
        rules: [{
          required: true,
          message: '请输入',
          trigger: 'blur'
        }]

      }
    },
    {
      label: "上级菜单",
      prop: "parent_menu_id",
      hiden: true,
      form: {
        newRow: true,
        // slot: true,
        component: "el-cascader",
        rules: [],
        componentProps: {
          "show-all-levels": false,
          clearable: true,
          options: [{
            route_id: 0,
            title: "无",
          }],
          placeholder: "选择上级菜单",
          props: {
            value: 'route_id',
            label: 'title',
            children: 'children',
            checkStrictly: true,
            expandTrigger: 'hover',
          }
        },
        options: {
          list: [],
          // valueKey:"route_id",
          valueField: "route_id",
          filter(val, list) {
            // console.log(val);
            if (val == '0') {
              return "无"
            } else {
              // console.log(list);
              const a = list[val]
              return a ? a['title'] : "未知"
            }
          }
        }

      }
    },
    {
      label: "上级菜单",
      prop: "parent_title",

      form: {
        addDisplay: false,
        editDisplay: false
      }
    },
    {
      label: "图标",
      prop: "icon",
      overflow: true,
      form: {
        component:"base-icon-select",
        componentProps: {
          placeholder: "请输入图标名称"
        }
      }
    },
   
    {
      label: "path",
      prop: "path",
      overflow:true,
      width:"120px",
      form: {
        newRow: true,
        component: "el-input",
        componentProps: {
          placeholder: "访问路由/name 当前路由层级名称"
        },
        rules: [{
          required: true,
          message: '请输入',
          trigger: 'blur'
        }]
      }
    },
    {
      // 基于前端组件views文件夹
      label: "组件路径",
      prop: "component",
      overflow:true,
      width:"120px",
      form: {
        component: "el-input",
        componentProps: {
          placeholder: "组件路径，一级/，子级如sys/menus"
        },
        rules: [{
          required: true,
          message: '请输入',
          trigger: 'blur'
        }]
      }
    },
    {
      label:"组件名称",
      prop:"component_name",
      overflow:true,
      width:"120px",
      copy:true,
      form:{
        component:"el-input",
        componentProps:{
          placeholder: "组件名称，需与name选项一致，否则缓存不生效"
        }
      }
    },
    {
      label: "激活菜单",
      prop: "active_menu",
      overflow:true,
      width:"120px",
      form: {
        component: "el-input",
        componentProps: {
          placeholder: "当前路由激活左侧菜单的路径，默认已激活自身"
        }
      }
    },
    {
      label:"重定向",
      prop:"redirect",
      overflow:true,
      width:"120px",
      form: {
        component: "el-input",
        componentProps: {
          placeholder: "路由重定向"
        }
      }
    },
    {
      label: "排序号",
      prop: "order",
      form: {
        component: "el-input-number",
      }
    },
   
    {
      label:"隐藏菜单",
      prop:"is_hidden",
      form:{
        component:"el-switch",
        newRow:true,
        span:8,
        componentProps:{},
      }
    },
   
    {
      label:"不缓存",
      prop:"no_cache",
      form:{
        component:"el-switch",
        span:8,
        labelWidth:"114px",
        // labelWidth:"58px",
        componentProps:{
          // activeText:"不缓存",
          // inactiveText:"缓存"
        }
      }
    },
    {
      label:"固定tag",
      prop:"affix",
      form:{
        component:"el-switch",
        span:8,
        componentProps:{
          // activeText:"不缓存",
          // inactiveText:"缓存"
        }
      }
    },
    {
      label:"面包屑显示",
      prop:"breadcrumb",
      form:{
        component:"el-switch",
        span:8,
        // labelWidth:"94px",
        componentProps:{
          // activeText:"不缓存",
          // inactiveText:"缓存"
        }
      }
    },
    {
      label: "根路由总是显示",
      prop: "always_show",
      hiden: false,
      overflow: true,
      form: {
        component: "el-switch",
        labelWidth: "114px",
        span:8,
        newRow:false,
        componentProps: {

        },
      }
    },
  ]



  // setups.root.$message({
  //   message:"hello",type:'error',
  //   duration:30000
  // })
  return {
    ...cruds,
    crudObj,
  }
}


function useLeftTree(setups, cruds) {
  const treeRef = ref(null)
  const tree = reactive({
    data: [],
    props: {
      label: "title",
      children: "children"
    },
    filterMsg: "",
  })

  // 实现过滤功能。
  watch(() => tree.filterMsg, (nv, ov) => {
    // console.log(nv);
    treeRef.value.filter(nv);
  })

  /** 树节点过滤 */
  const filterNode = (value, data) => {
    if (!value) return true;
    return data.title.indexOf(value) !== -1;
  }

  // 递归获取一个树的所有route_id
  function getNodeRouteId(node, getList = []) {
    getList.push(node.route_id);
    if (node.children && node.children.length > 0) {
      node.children.forEach(item => {
        getNodeRouteId(item, getList)
      })
    }
  }

  /** 树节点点击 */
  const nodeClick = (node) => {
    // console.log(node);
    // cruds.loading.value = true;
    const idList = [];
    getNodeRouteId(node, idList);
    // console.log(idList);
    // console.log(cruds);
    // 在条件数组上挂载一个数据。
    cruds.condition.value.idList = idList;
    cruds.refresh();

  }


  const treeHeight = computed(() => {
    return window.hei.value - 198 + 'px';
  })

  tree.nodeClick = nodeClick;
  tree.filterNode = filterNode;
  return {
    tree,
    treeRef,
    treeHeight,
  }
}
